package cn.yhjz.platform.system.repository;

import cn.yhjz.platform.system.entity.LogedUserDetails;
import cn.yhjz.platform.system.util.RedisUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 用于操作token的类
 */
@Component
public class UserPrincipalRepository {

    public static final String TOKEN_KEY_PREFIX = "system:jwt:";
    @Value("${system.redis-token-timeout}")
    private long redis_timeout;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 保存token
     * 以token为key持久化用户信息
     */
    public void save(String usercode, LogedUserDetails principal) {
        redisUtil.set(TOKEN_KEY_PREFIX + usercode, principal, redis_timeout);
    }

    /**
     * 获得用户的验证和授权对象
     *
     * @param usercode
     */
    public LogedUserDetails get(String usercode) {
        String json = redisUtil.get(TOKEN_KEY_PREFIX + usercode);
        if (StrUtil.isEmpty(json)) {
            return null;
        }
        LogedUserDetails principal = JSON.parseObject(json, LogedUserDetails.class);
        return principal;
    }

    /**
     * 刷新token的生命周期
     *
     * @param usercode
     */
    public void expire(String usercode) {
        redisUtil.expire(TOKEN_KEY_PREFIX + usercode, redis_timeout);
    }


    /**
     * 获得用户的验证和授权对象
     *
     * @param usercode
     */
    public LogedUserDetails getAndExpire(String usercode) {
        LogedUserDetails principal = this.get(usercode);
        if (principal != null) {
            this.expire(usercode);
            return principal;
        }
        return null;
    }

    /**
     * 删除
     * @param usercode
     */
    public void remove(String usercode) {
        redisUtil.delete(TOKEN_KEY_PREFIX + usercode);
    }

}
